package com.jz.yanshe.ui;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.jz.jd.rest.business.RestProxy;
import com.jz.jd.rest.exception.BusinessException;
import com.jz.jd.rest.response.BaseResponse;
import com.jz.jd.rest.response.ExpressPriceResponse;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnLongClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import com.jz.yanshe.eventbus.OrderRefreshEvent;
import com.jz.yanshe.util.ImageLoaderHelper;
import com.jz.yanshe.util.UriUtils;
import jz.com.feierman.R;

import com.jz.yanshe.base.BaseActivity;
import com.jz.yanshe.util.PreferencesHelper;

import static android.content.ContentValues.TAG;

/**
 * Created by Administrator on 2018/3/14.
 */

public class UploadOrderFileActivity extends BaseActivity{

    @BindView(R.id.img1)
    ImageView img1;

    @BindView(R.id.img2)
    ImageView img2;

    @BindView(R.id.img3)
    ImageView img3;

    @BindView(R.id.btn_add_1)
    ImageView btn_add_1;

    @BindView(R.id.btn_add_2)
    ImageView btn_add_2;

    @BindView(R.id.btn_add_3)
    ImageView btn_add_3;

    @BindView(R.id.btn_del_1)
    ImageView btn_del_1;

    @BindView(R.id.btn_del_2)
    ImageView btn_del_2;

    @BindView(R.id.btn_del_3)
    ImageView btn_del_3;

    @BindView(R.id.edt_remark)
    EditText edt_remark;

    @BindView(R.id.tv_bank_num)
    TextView tv_bank_num;

    @BindView(R.id.tv_price)
    TextView tv_price;

    @BindView(R.id.parent_container)
    LinearLayout parent_container;


    String path1, path2, path3,orderid,pay_price;

    ProgressDialog dialog;

    @BindView(R.id.img_alipay)
    ImageView img_alipay;

    @BindView(R.id.img_wechat)
    ImageView img_wechat;

    @Override
    protected void initViews() {

    }

    @Override
    protected void initData() {
        orderid = getIntent().getStringExtra("orderid");
        pay_price = getIntent().getStringExtra("pay_price");
        tv_price.setText("¥" +String.format("%.2f",Double.valueOf(pay_price)));
        getWeChat();
        getAliPayUrl();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_upload_order_file;
    }



    @OnClick(R.id.btn_add_1)
    void btn_add_1() {
        openGallery(1);
    }

    @OnClick(R.id.btn_add_2)
    void btn_add_2() {
        openGallery(2);
    }

    @OnClick(R.id.btn_add_3)
    void btn_add_3() {
        openGallery(3);
    }

    @OnClick(R.id.btn_del_1)
    void btn_del_1(){
        img1.setImageDrawable(null);
        btn_add_1.setVisibility(View.VISIBLE);
        btn_del_1.setVisibility(View.INVISIBLE);
        path1 = "";
    }

    @OnClick(R.id.btn_del_2)
    void btn_del_2(){
        img2.setImageDrawable(null);
        btn_add_2.setVisibility(View.VISIBLE);
        btn_del_2.setVisibility(View.INVISIBLE);
        path2 = "";
    }

    @OnClick(R.id.btn_del_3)
    void btn_del_3(){
        img3.setImageDrawable(null);
        btn_add_3.setVisibility(View.VISIBLE);
        btn_del_3.setVisibility(View.INVISIBLE);
        path3 = "";
    }

    @OnClick(R.id.btn_confirm)
    void btn_confirm() {
        uploadVipFile();
    }


    protected void openGallery(int requestCode) {

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    10);

        } else {
            choosePhoto(requestCode);
        }


    }

    private void choosePhoto(int requestCode) {
        Intent intent = new Intent();
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            intent.setAction(Intent.ACTION_PICK);
//            intent.setType("image/*");//相片类型
        } else {
            intent.setAction(Intent.ACTION_GET_CONTENT);
//            intent.setAction(Intent.ACTION_PICK);
        }
        intent.setType("image/*");
        startActivityForResult(intent, requestCode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (data != null) {
                    Uri imgUriSel = data.getData();
                    String imgPathSel = UriUtils.formatUri(this, imgUriSel);

                    Log.i(TAG, "Kit_sel_path:" + imgPathSel);
                    Log.i(TAG, "openGalleryResult_imgUriSel:" + imgUriSel);
//                    uploadFile(imgPathSel);
                    path1 = imgPathSel;
                    ImageLoaderHelper.getInstance().GlideImageLoader(this, imgPathSel, img1);
                    btn_add_1.setVisibility(View.INVISIBLE);
                    btn_del_1.setVisibility(View.VISIBLE);
                }
                break;
            case 2:
                if (data != null) {
                    Uri imgUriSel = data.getData();
                    String imgPathSel = UriUtils.formatUri(this, imgUriSel);

                    Log.i(TAG, "Kit_sel_path:" + imgPathSel);
                    Log.i(TAG, "openGalleryResult_imgUriSel:" + imgUriSel);
//                    uploadFile(imgPathSel);
                    path2 = imgPathSel;
                    ImageLoaderHelper.getInstance().GlideImageLoader(this, imgPathSel, img2);
                    btn_add_2.setVisibility(View.INVISIBLE);
                    btn_del_2.setVisibility(View.VISIBLE);
                }
                break;
            case 3:
                if (data != null) {
                    Uri imgUriSel = data.getData();
                    String imgPathSel = UriUtils.formatUri(this, imgUriSel);

                    Log.i(TAG, "Kit_sel_path:" + imgPathSel);
                    Log.i(TAG, "openGalleryResult_imgUriSel:" + imgUriSel);
//                    uploadFile(imgPathSel);
                    path3 = imgPathSel;
                    ImageLoaderHelper.getInstance().GlideImageLoader(this, imgPathSel, img3);
                    btn_add_3.setVisibility(View.INVISIBLE);
                    btn_del_3.setVisibility(View.VISIBLE);
                }
                break;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 10) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                choosePhoto();
            } else {
                // Permission Denied
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void uploadVipFile() {
        File file1 = null;
        File file2 = null;
        File file3 = null;
        if (path1 != null && !path1.equals("")) {
            file1 = new File(path1);
        }
        if (path2 != null && !path2.equals("")) {
            file2 = new File(path2);
        }
        if (path3 != null && !path3.equals("")) {
            file3 = new File(path3);
        }
        RestProxy.getInstance().uploadFile(PreferencesHelper.getInstance().getString(this, "token"), file1, file2, file3,edt_remark.getText().toString(),orderid, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
                dialog  = ProgressDialog.show(UploadOrderFileActivity.this, "提示", "正在上传中…", true, false, null);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                Toast.makeText(UploadOrderFileActivity.this, baseResponse.message, Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                dialog.dismiss();
                Toast.makeText(UploadOrderFileActivity.this,((BusinessException)e).errorDescription, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete() {
                dialog.dismiss();
                EventBus.getDefault().postSticky(new OrderRefreshEvent("1"));
            }
        });
    }

    @OnClick(R.id.btn_copy)
    void btn_copy(){
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData mClipData = ClipData.newPlainText("Label", tv_bank_num.getText().toString());
// 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
        Toast.makeText(this, "复制成功", Toast.LENGTH_SHORT).show();
    }


    private void getAliPayUrl() {
        RestProxy.getInstance().getAliPayUrl(new Observer<ExpressPriceResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ExpressPriceResponse expressPriceResponse) {
                ImageLoaderHelper.getInstance().GlideImageLoader(UploadOrderFileActivity.this, expressPriceResponse.entity.common_configuration_description, img_alipay);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void getWeChat() {
        RestProxy.getInstance().getWeChatUrl(new Observer<ExpressPriceResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ExpressPriceResponse expressPriceResponse) {
                ImageLoaderHelper.getInstance().GlideImageLoader(UploadOrderFileActivity.this, expressPriceResponse.entity.common_configuration_description, img_wechat);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    @OnLongClick(R.id.img_alipay)
    boolean img_alipay() {
        Bitmap obmp = ((BitmapDrawable) (img_alipay.getDrawable())).getBitmap();
        int width = obmp.getWidth();
        int height = obmp.getHeight();
        int[] data = new int[width * height];
        obmp.getPixels(data, 0, width, 0, 0, width, height);
        RGBLuminanceSource source = new RGBLuminanceSource(width, height, data);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        new QrCodeAsyncTask().execute(bitmap);
        return true;
    }


    @OnLongClick(R.id.img_wechat)
    boolean img_wechat() {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                // 要在运行在子线程中
                Bitmap obmp = ((BitmapDrawable) (img_wechat.getDrawable())).getBitmap();
                savePicture(obmp, System.currentTimeMillis()+".jpg");// 保存图片
                img_wechat.destroyDrawingCache(); // 保存过后释放资源
            }
        },100);
        return true;
    }

    public void savePicture(Bitmap bm, String fileName) {
        verifyStoragePermissions(this);

        Log.i("xing", "savePicture: ------------------------");
        if (null == bm) {
            Log.i("xing", "savePicture: ------------------图片为空------");
            return;
        }
        File foder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test");
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(foder, fileName);
        try {
            if (!myCaptureFile.exists()) {
                myCaptureFile.createNewFile();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            //压缩保存到本地
            bm.compress(Bitmap.CompressFormat.JPEG, 90, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "权限不足!", Toast.LENGTH_SHORT).show();
            return;
        }
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myCaptureFile)));
        Toast.makeText(this, "保存成功!", Toast.LENGTH_SHORT).show();
    }
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    public  void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }


    class QrCodeAsyncTask extends AsyncTask<BinaryBitmap, Void, Result> {

        @Override
        protected Result doInBackground(BinaryBitmap... params) {
            QRCodeReader reader = new QRCodeReader();
            Result result = null;
            try {
                result = reader.decode(params[0]);
            } catch (NotFoundException e) {
                e.printStackTrace();
            } catch (ChecksumException e) {
                e.printStackTrace();
            } catch (FormatException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(Result result) {
            super.onPostExecute(result);

            String text = result.getText();
//            Logger.info(TAG, "QR CODE: " + text);
            Toast.makeText(UploadOrderFileActivity.this, "正在跳转..", Toast.LENGTH_SHORT).show();
            Bundle bundle = new Bundle();
            bundle.putString("url",text);

            startActivity(WebViewActivity.class,bundle);
        }

    }
}
